<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title.sync="title" width="940px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="125px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="所属服务商" prop="serviceproviderId">
            <el-select v-model="form.serviceproviderId" placeholder="所属服务商" style="width:760px;" :disabled="isView">
              <el-option v-for="(item,index) in serviceproItem" :key="index" :label="item.seproName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="personPassword">
            <el-input
              v-model="form.personPassword"
              type="password"
              placeholder="请输入密码"
              maxlength="18"
              :show-password="true"
              :readonly="isView"
              style="width: 300px;"
              auto-complete="new-password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="personName">
            <el-input v-model="form.personName" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地区" prop="province" :rules="{ required: form.state === 0, message: '请选择地区' }">
            <AreaSelect ref="areaSelect" :default-props="form" @change="handleSelectArea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类别" prop="major" :rules="{ required: form.state === 0, message: '请选择类别' }">
            <el-select v-model="form.major" class="input_text" placeholder="请选择">
              <el-option
                v-for="item in majors"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="等级" prop="level" :rules="{ required: form.state === 0, message: '请选择等级' }">
            <el-select v-model="form.level" class="input_text" placeholder="请选择">
              <el-option
                v-for="item in levels"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="isView===false || isAdd===true" type="text" @click="cancel">取消</el-button>
      <el-button v-show="isAdd===false && isView===true" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="isView===false" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { add, edit } from '@/api/tServiceproviderPerson'
import AreaSelect from '@/components/AreaSelect'
import md5 from 'md5'
import { EngineerMajors, EngineerLevels } from '@/constants/consts'
import { isvalidPhone } from '@/utils/validate'

export default {
  components: {
    AreaSelect
  },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入正确的11位手机号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      dialog: false,
      title: '',
      form: {
        id: '',
        personName: '',
        personPassword: '',
        personPasswordOrigin: '',
        account: '',
        phone: '',
        serviceproviderId: '',
        serviceproviderName: '',
        creatTime: '',
        state: 1,
        techLevel: '',
        major: '',
        level: '',
        country: '',
        province: '',
        city: '',
        county: ''
      },
      admins: [
        {
          id: 1,
          name: '是'
        },
        {
          id: 0,
          name: '否'
        }
      ],
      serviceproItem: [],
      techLevels: [],
      rules: {
        personName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        personPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        serviceproviderId: [
          { required: true, message: '请选择服务商', trigger: 'blur' }
        ]
      },
      majors: EngineerMajors,
      levels: EngineerLevels,
      region: []
    }
  },
  mounted: function() {
    this.byNameTechLevel('技能水平')
    this.tServiceproviderInfoAll()
    this.title = this.isAdd ? '新增' : (this.isView === true ? '详情' : '编辑')
  },
  methods: {
    handleSelectArea(countryItem, provinceItem, cityItem, areaItem) {
      this.form.country = countryItem.name
      this.form.province = provinceItem.name
      this.form.city = cityItem.name
      this.form.county = areaItem.name
    },
    tServiceproviderInfoAll() {
      this.getAllService().then(res => {
        this.serviceproItem = res
      })
    },
    getAllService() {
      return request({
        url: 'api/tServiceproviderInfoAll',
        method: 'get'
      })
    },
    byNameTechLevel(name) {
      this.byName(name).then(res => {
        if (res.id) {
          this.bydictId(res.id).then(resobject => {
            this.techLevels = resobject
          })
        }
      })
    },
    // 获取id值
    byName(name) {
      return request({
        url: 'api/dict/byName/' + name,
        method: 'get'
      })
    },
    // 获取id值
    bydictId(id) {
      return request({
        url: 'api/dictDetail/findByDeptId/' + id,
        method: 'get'
      })
    },
    // ----------------------
    indexSelect(event) {

    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isAdd) {
            this.form.personPassword = md5(this.form.personPassword)
            this.doAdd()
          } else {
            if (this.form.personPassword !== this.form.personPasswordOrigin) { // 修改密码，重新md5
              this.form.personPassword = md5(this.form.personPassword)
            }
            this.doEdit()
          }
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.$refs['areaSelect'] && this.$refs['areaSelect'].clear()
      this.form = {
        id: '',
        personName: '',
        personPassword: '',
        personPasswordOrigin: '',
        account: '',
        phone: '',
        serviceproviderId: '',
        serviceproviderName: '',
        creatTime: '',
        techLevel: '',
        major: '',
        level: '',
        country: '',
        province: '',
        city: '',
        county: ''
      }
    }
  }
}
</script>

<style scoped>
.input_text {
  width: 300px
}
</style>
